package mall.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import mall.pojo.Product;

@Repository
public class ProductDAOImpl implements ProductDAO {
	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public void createProduct(Product product) {
		product.setQuantity(product.getQuantity()+1);
		sessionFactory.getCurrentSession().save(product);
	}

	@Override
	public int updateProduct(Product product) {
		//String hql = "UPDATE Product SET description = :description , kind = :kind , name = :name , picture = :picture , price = :price WHERE id = :id";
		String hql = "UPDATE Product SET description = :description , kind = :kind , name = :name, price = :price, quantity = :quantity WHERE id = :id";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setParameter("description", product.getDescription());
		query.setParameter("kind", product.getKind());
		query.setParameter("name", product.getName());
		//query.setParameter("picture", product.getPicture());
		query.setParameter("price", product.getPrice());
		query.setParameter("quantity", product.getQuantity());
		query.setParameter("id", product.getId());
		return query.executeUpdate();
	}

	@Override
	public int deleteProduct(int productId) {
		String hql="DELETE Product WHERE id ='"+productId+"'";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		return query.executeUpdate();
	}

	@Override
	public List<Product> getProductShop(int shopId,int catId,int kind) {
		String hql="FROM Product P WHERE P.shop.id = :shopId AND P.category.id=:catId AND P.kind = :kind";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setParameter("shopId", shopId);
		query.setParameter("catId", catId);
		query.setParameter("kind", kind);
		return (List<Product>)query.list();
	}

	@Override
	public Product getProduct(int productId) {
		String hql="FROM Product P WHERE P.id = "+productId+"";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		return (Product)query.list().get(0);
	}

	@Override
	public List<Product> getListProduct() {
		String hql="FROM product  ";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		return (List<Product>)query.list();
	}

}
